<?php
namespace app\middleware;

use app\helper\JwtHelper;
use ReflectionClass;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;

class AuthCheck implements MiddlewareInterface
{
    public function process(Request $request, callable $handler): Response
    {
        // 通过反射获取控制器哪些方法不需要登录
        $controller = new ReflectionClass($request->controller);
        $noNeedLogin = $controller->getDefaultProperties()['noNeedLogin'] ?? [];

        // 访问的方法需要登录
        if (!in_array($request->action, $noNeedLogin)) {
            $jwtController = new JwtHelper;
            $jwt = $request->header('jwt');
            if (!$jwt) {
                return json(["code" => 400, "msg" => "请先登录"]);
            }
            $decoded = $jwtController->decode($jwt);
            if ($decoded) {
                // 已经登录，请求继续向洋葱芯穿越
                return $handler($request);
            }
            // 拦截请求，返回一个重定向响应，请求停止向洋葱芯穿越
            return json(["code" => 400, "msg" => "请先登录"]);
        }

        // 不需要登录，请求继续向洋葱芯穿越
        return $handler($request);
    }
}
